package com.onepower.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.onepower.core.domain.response.MatchScheduleInfo;
import com.onepower.core.domain.response.MatchScoreInfo;
import com.onepower.core.domain.response.RefereeInfo;
import com.onepower.core.domain.response.SysUserInfo;
import com.onepower.core.modules.repository.entity.*;
import com.onepower.core.modules.service.*;
import com.onepower.core.result.CommonResult;
import com.onepower.core.utils.ResultUtils;
import com.onepower.core.utils.SecurityUtils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;

/**
 * <p>
 * 比赛分数表 前端控制器
 * </p>
 *
 * @author kin
 * @since 2018-08-12
 */
@RestController
@RequestMapping("/api/match/score")
public class MatchScoreController {

    @Autowired
    private IMatchScoreService matchScoreService;

    @Autowired
    private IMatchScheduleLogicScoreService matchScheduleLogicScoreService;


    @Autowired
    private IMatchScoreArithmeticRuleService matchScoreArithmeticRuleService;

    @Autowired
    private IMatchScheduleService matchScheduleService;

    @Autowired
    private IMatchRefereeService matchRefereeService;

    @Autowired
    private RedisTemplate<Serializable, Object> redisTemplate;

    @Autowired
    private IMatchScoreOrderRuleService matchScoreOrderRuleService;

    @Autowired
    private ISysUserService userService;

    @Autowired
    HttpServletRequest request;

    @RequestMapping(value = "/info")
    public CommonResult getMatchScore(@RequestParam int matchId,
                                      @RequestParam int matchAdminId) {
        MatchScoreInfo scoreInfo = matchScoreService.getMatchScore(matchId, matchAdminId);
        return ResultUtils.ok(scoreInfo);
    }

    @RequestMapping(value = "/matchRefereeScore")
    public CommonResult matchRefereeScore(@RequestParam int matchScheduleId,
                                          @RequestParam int refereeId,
                                          @RequestParam int scoreType) {

        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        MatchScore score = matchScoreService.matchRefereeScore(matchScheduleId,refereeId,matchScheduleInfo.getLockTwoTime());
        return ResultUtils.ok(score);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public CommonResult save(@RequestBody MatchScore matchScore) {
        matchScoreService.save(matchScore);
        return new CommonResult();
    }

    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public CommonResult delete(@RequestBody Integer[] scoreIds) {
        matchScoreService.removeByIds(Arrays.asList(scoreIds));
        return new CommonResult();
    }

    @RequestMapping(value = "/updateSocre", method = RequestMethod.POST)
    public CommonResult updateSocre(@RequestParam(value = "id",defaultValue = "-1",required = false) int id,
                                    @RequestParam(value = "expressiveness",required = false, defaultValue = "-1") double expressiveness,
                                    @RequestParam(value = "accuracy", required = false, defaultValue = "-1") double accuracy,
                                    @RequestParam(value = "winner", required = false,defaultValue = "-1") int winner,
                                    @RequestParam(value = "matchScheduleId") int matchScheduleId,
                                    @RequestParam(value = "refereeId") int refereeId,
                                    @RequestParam(value = "referee") String referee,
                                    @RequestParam(value = "scoreType") int scoreType
                                    ) {
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);

        MatchScore matchScore = new MatchScore();
       
        //临时方案,检验确定按钮重新添加的情况
        QueryWrapper<MatchScore> qw = new QueryWrapper<MatchScore>();
        qw.eq("referee_id", refereeId);
        qw.eq("match_schedule_id", matchScheduleId);
        MatchScore matchScore2 = matchScoreService.getOne(qw);
        if(matchScore2 != null) {
        	matchScore.setId(matchScore2.getId());
        }
        
        if (expressiveness != -1.0){
            matchScore.setExpressiveness(expressiveness);
            matchScore.setAccuracy(accuracy);
        }else if (!matchScheduleInfo.getTwoTime() && matchScheduleInfo.getType() == 2){
            if (winner == -1){
                return ResultUtils.error(500,"请选择");
            }
            matchScore.setWinner(winner);
        }
       
        if (id != -1){
            matchScore.setId(id);
        }else {
            matchScore.setMatchScheduleId(matchScheduleId);
            matchScore.setRefereeId(refereeId);
            matchScore.setReferee(referee);
            matchScore.setScoreType(scoreType);
        }
        boolean b = matchScoreService.saveOrUpdate(matchScore);
        return ResultUtils.ok(b);
    }

    @RequestMapping(value = "/deleteById", method = RequestMethod.POST)
    public CommonResult delete(@RequestParam(value = "id") int id) {
        boolean b = matchScoreService.removeById(id);
        return ResultUtils.ok(b);
    }

    @RequestMapping(value = "/avgScore", method = RequestMethod.POST)
    public CommonResult avgScore(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                 @RequestParam(value = "type") int type) {
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        Map<String,Object> avgScore = matchScoreService.avgScore(matchScheduleId,matchScheduleInfo.getLockTwoTime()+1);
        return ResultUtils.ok(avgScore);
    }

    @RequestMapping(value = "/logicScore", method = RequestMethod.POST)
    public CommonResult logicScore(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                   @RequestParam(value = "refereeType") int refereeType,
                                   @RequestParam(value = "type") int type) {

        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        MatchScheduleLogicSocre matchScheduleLogicSocre = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,type);
        if (matchScheduleLogicSocre == null){
            matchScheduleLogicSocre = new MatchScheduleLogicSocre();
            matchScheduleLogicSocre.setType(type);
            matchScheduleLogicSocre.setMatchScheduleId(matchScheduleId);
            matchScheduleLogicSocre.setCreateTime(new Date());
            matchScheduleLogicSocre.setIsShow(0);
            matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
        }
        if (matchScheduleInfo.getType() == 1 || (matchScheduleInfo.getType() == 2 && matchScheduleInfo.getTwoTime())){
            MatchScoreArithmeticRule matchScoreArithmeticRule =  matchScoreArithmeticRuleService.arithmeticRule(refereeType);
            if (matchScoreArithmeticRule.getArithmeticRuleId() == 1){
                Map<String,Object> sumScore = matchScoreService.sumScore(matchScheduleId,type);  //求全和
                matchScheduleLogicSocre.setAccuracyScore((Double) sumScore.get("sumA"));
                matchScheduleLogicSocre.setExpressivenessScore((Double) sumScore.get("sumP"));
                matchScheduleLogicSocre.setTotalScore((Double) sumScore.get("sumA") + (Double) sumScore.get("sumP") );
                matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                matchScheduleLogicScoreService.saveOrUpdate(matchScheduleLogicSocre);
            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 2){
                Map<String,Object> avgScore = matchScoreService.avgScore(matchScheduleId,type);
                matchScheduleLogicSocre.setAccuracyScore((Double) avgScore.get("avgA"));
                matchScheduleLogicSocre.setExpressivenessScore((Double) avgScore.get("avgP"));
                matchScheduleLogicSocre.setTotalScore((Double) avgScore.get("avgA") + (Double) avgScore.get("avgP") );
                matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);

            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 3){
                Map<String,Object> sumScore = matchScoreService.sumScore(matchScheduleId,type);  //精准度求和	, 表现力求和
                matchScheduleLogicSocre.setAccuracyScore((Double) sumScore.get("sumA"));
                matchScheduleLogicSocre.setExpressivenessScore((Double) sumScore.get("sumP"));
                matchScheduleLogicSocre.setTotalScore((Double) sumScore.get("sumA") + (Double) sumScore.get("sumP") );
                matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);

            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 4){
                Map<String,Object> removeMaxAndMinAvgExpressiveness = matchScoreService.removeMaxAndMinAvgExpressiveness(matchScheduleId,type);//表现力去峰值求平均
                Map<String,Object> avgScore = matchScoreService.avgScore(matchScheduleId,type);//取精准度平均
                matchScheduleLogicSocre.setAccuracyScore((Double) avgScore.get("avgA"));
                matchScheduleLogicSocre.setExpressivenessScore((Double) removeMaxAndMinAvgExpressiveness.get("avgP"));
                matchScheduleLogicSocre.setTotalScore((Double) avgScore.get("avgA") + (Double) removeMaxAndMinAvgExpressiveness.get("avgP") );
                matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);

            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 5){
                Map<String,Object> removeMaxAndMinAvgAccuracy = matchScoreService.removeMaxAndMinAvgAccuracy(matchScheduleId,type);//准度去峰值求平均
                Map<String,Object> avgScore = matchScoreService.avgScore(matchScheduleId,type);//取表现力平均
                matchScheduleLogicSocre.setAccuracyScore((Double) removeMaxAndMinAvgAccuracy.get("avgA"));
                matchScheduleLogicSocre.setExpressivenessScore((Double) avgScore.get("avgP"));
                matchScheduleLogicSocre.setTotalScore((Double) avgScore.get("avgP") + (Double) removeMaxAndMinAvgAccuracy.get("avgA") );
                matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);

            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 6){
                double accuracySum = 0;
                double expressivenessSum = 0;

                List<Map<String,Object>> orderAccuracyList = matchScoreService.orderAccuracy(matchScheduleId,type);
                List<Map<String,Object>> orderExpressivenessList = matchScoreService.orderExpressiveness(matchScheduleId,type);
                if (orderAccuracyList.size()> 1){
                    for (int i=1;i<orderAccuracyList.size()-1;i++){
                        accuracySum += (double)orderAccuracyList.get(i).get("accuracy");
                    }
                    for (int i=1;i<orderExpressivenessList.size()-1;i++){
                        expressivenessSum += (double)orderExpressivenessList.get(i).get("expressiveness");
                    }
                    //double avg =  (accuracySum + expressivenessSum)/(orderAccuracyList.size()-2);
                    BigDecimal a = new BigDecimal(accuracySum/(orderAccuracyList.size()-2));
                    BigDecimal b = new BigDecimal(expressivenessSum/(orderExpressivenessList.size()-2));
                    matchScheduleLogicSocre.setTotalScore(a.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() + b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    matchScheduleLogicSocre.setExpressivenessScore(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    matchScheduleLogicSocre.setAccuracyScore(a.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
                    matchScheduleLogicSocre.setMatchId(matchScheduleInfo.getMatchId());
                    matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                    matchScheduleLogicScoreService.save(matchScheduleLogicSocre);
                }else {
                    return ResultUtils.error(900,"裁判未超过两人");
                }
                /*Map<String,Object> removeMaxAndMinSumSocre = matchScoreService.removeMaxAndMinSumSocre(matchScheduleId);  //准确度+表现力之和去峰值求平均
                matchScheduleLogicSocre.setTotalScore((Double) removeMaxAndMinSumSocre.get("avgSocre"));
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);*/
            }else if (matchScoreArithmeticRule.getArithmeticRuleId() == 7){
                Map<String,Object> removeMaxAndMinSumSocre = matchScoreService.removeMaxAndMinSumSocre(matchScheduleId,type);  //准确度+表现力之和去峰值求平均
                matchScheduleLogicSocre.setTotalScore((Double) removeMaxAndMinSumSocre.get("avgSocre"));
                matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
                matchScheduleLogicScoreService.save(matchScheduleLogicSocre);
            }
            matchComplate(matchScheduleId,matchScheduleInfo.getTwoTime(),matchScheduleInfo.getLockTwoTime());
            return ResultUtils.ok();
        }else if (matchScheduleInfo.getType() == 2 && !matchScheduleInfo.getTwoTime()){
            Map<String,Object> winnerCount = matchScoreService.matchScoreWinnerCount(matchScheduleId,type);

            matchScheduleLogicSocre.setWinner0(Integer.valueOf(winnerCount.get("winner0").toString()));
            matchScheduleLogicSocre.setWinner1(Integer.valueOf(winnerCount.get("winner1").toString()));
            matchScheduleLogicScoreService.saveOrUpdate(matchScheduleLogicSocre);
           // matchScheduleLogicScoreService.deleteByIdAndType(matchScheduleId,type);
           // matchScheduleLogicScoreService.save(matchScheduleLogicSocre);
            matchComplate(matchScheduleId,matchScheduleInfo.getTwoTime(),matchScheduleInfo.getLockTwoTime());
            return ResultUtils.ok();
        }
        return ResultUtils.error(501,"裁判未提交成绩");
    }

    private void matchComplate(int matchScheduleId,boolean towTime,int lockTwoTime){
        MatchSchedule matchSchedule = new MatchSchedule();
        matchSchedule.setId(matchScheduleId);
        matchSchedule.setIsComplete(1);
        matchSchedule.setTwoTime(towTime);
        matchSchedule.setLockTwoTime(lockTwoTime);
        SysUserInfo userInfo = userService.getUser(SecurityUtils.getCurrentUserId(request));
        matchSchedule.setFinalUser(userInfo.getNickName());
        matchScheduleService.updateById(matchSchedule);
    }

    @RequestMapping(value = "/showLogicSocre", method = RequestMethod.POST)
    public CommonResult showLogicSocre(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                       @RequestParam(value = "type") int type
                                       ){
        matchScheduleLogicScoreService.updateScheduleLogicScore(matchScheduleId, type);
        return ResultUtils.ok();
    }

    @RequestMapping(value = "/getLogicScore", method = RequestMethod.POST)
    public CommonResult getLogicScore(@RequestParam(value = "matchScheduleId") int matchScheduleId
                                      ) {

    //    MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        List<MatchScheduleLogicSocre> list = matchScheduleLogicScoreService.scheduleLogicScoreList(matchScheduleId);
        return ResultUtils.ok(list);
    }


    @RequestMapping(value = "/totlaLogicScore", method = RequestMethod.POST)
    public CommonResult totlaLogicScore(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                        @RequestParam(value = "scheduleType") int scheduleType,
                                        @RequestParam(value = "scoreType", required = true) int scoreType) {
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        if (matchScheduleInfo.getType() == 1 && !matchScheduleInfo.getTwoTime()){
            MatchScheduleLogicSocre msls  = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,matchScheduleInfo.getLockTwoTime());
            Double A = Double.valueOf(0);
            Double P = Double.valueOf(0);
            Double T = Double.valueOf(0);
            Map<String,Object> map = new HashMap<>();
            map.put("T",T);
            map.put("A",A);
            map.put("P",P);
            if (msls != null){
                T = T + msls.getTotalScore();
                A = A + msls.getAccuracyScore();
                P = P +  msls.getExpressivenessScore();
                map.put("T",T);
                map.put("A",A);
                map.put("P",P);
            }

            return ResultUtils.ok(map);
        }else if (matchScheduleInfo.getType() == 1 && matchScheduleInfo.getTwoTime()){
            MatchScheduleLogicSocre ms1 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,1);
            MatchScheduleLogicSocre ms2 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,2);
            if (ms1 != null && ms2 != null){
                Double T1 = Double.valueOf(0);
                Double T2 = Double.valueOf(0);
                Double T3 = Double.valueOf(0);
                Map<String,Object> map = new HashMap<>();
                T1 = (ms1.getAccuracyScore() + ms2.getAccuracyScore())/2;
                T2 = (ms1.getExpressivenessScore() + ms2.getExpressivenessScore())/2;
                T3 = (ms1.getTotalScore() + ms2.getTotalScore())/2;
                // 格式化保留1位小数
                NumberFormat nf = new DecimalFormat("0.0");
                map.put("T1",Double.parseDouble(nf.format(T1)));
                map.put("T2",Double.parseDouble(nf.format(T2)));
                map.put("T3",Double.parseDouble(nf.format(T3)));
                return ResultUtils.ok(map);
            }else {
                Map<String,Object> map = new HashMap<>();
                map.put("T1","");
                map.put("T2","");
                map.put("T3","");
                return ResultUtils.ok(map);
            }
        }else if (matchScheduleInfo.getType() == 2 && matchScheduleInfo.getTwoTime()){
            MatchScheduleLogicSocre ms1 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,1);
            MatchScheduleLogicSocre ms3 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,3);
            MatchScheduleLogicSocre ms2 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,2);
            MatchScheduleLogicSocre ms4 = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,4);
            if (ms1 != null && ms2 != null && ms3 != null && ms4 != null){
                Double T1 = Double.valueOf(0);  //青
                Double T2 = Double.valueOf(0);  //红
                Map<String,Object> map = new HashMap<>();
                T1 = (ms1.getTotalScore() + ms3.getTotalScore())/2;
                T2 = (ms2.getTotalScore() + ms4.getTotalScore())/2;
                // 格式化保留1位小数
                NumberFormat nf = new DecimalFormat("0.0");
                map.put("T1",Double.parseDouble(nf.format(T1)));
                map.put("T2",Double.parseDouble(nf.format(T2)));
                return ResultUtils.ok(map);
            }else {
                Map<String,Object> map = new HashMap<>();
                map.put("T1","");
                map.put("T2","");
                return ResultUtils.ok(map);
            }
        } else {
            MatchScheduleLogicSocre msls  = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,matchScheduleInfo.getLockTwoTime());
            Map<String,Object> map = new HashMap<>();
            Integer winner0 = 0;
            Integer winner1 = 0;
            map.put("winner0", winner0);
            map.put("winner1", winner1);
            if (msls != null){
                MatchScheduleLogicSocre matchScheduleLogicSocre = msls;
                winner0 = matchScheduleLogicSocre.getWinner0();
                winner1 = matchScheduleLogicSocre.getWinner1();
                map.put("winner0", winner0);
                map.put("winner1", winner1);
            }
            return ResultUtils.ok(map);
        }
    }

    /**
     * 总分公示
     * @param matchScheduleId
     * @return
     */
    @RequestMapping(value = "/totlaShowLogicScore", method = RequestMethod.POST)
    public CommonResult totlaShowLogicScore(@RequestParam(value = "matchScheduleId") int matchScheduleId,
                                            @RequestParam(value = "type") int type,
                                            @RequestParam(value = "scheduleType") int scheduleType
                                            ) {
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        MatchScheduleLogicSocre m = matchScheduleLogicScoreService.scheduleLogicScore(matchScheduleId,matchScheduleInfo.getLockTwoTime());
        if (m == null){
            Map<String,Object> map = new HashMap<>();
            Double A = Double.valueOf(0);
            Double P = Double.valueOf(0);
            Double T = Double.valueOf(0);
            map.put("T",T);
            map.put("A",A);
            map.put("P",P);
            return ResultUtils.ok(map);
        }else if (matchScheduleInfo.getType() == 1 || (matchScheduleInfo.getType() == 2 && matchScheduleInfo.getTwoTime())){
            Double A = Double.valueOf(0);
            Double P = Double.valueOf(0);
            Double T = Double.valueOf(0);
            Map<String,Object> map = new HashMap<>();
            if (m.getIsShow()  == 1){
                T = T + m.getTotalScore();
                A = A + m.getAccuracyScore();
                P = P +  m.getExpressivenessScore();
                map.put("T",T);
                map.put("A",A);
                map.put("P",P);
            }
            return ResultUtils.ok(map);
        }else if (matchScheduleInfo.getType()  == 2 && !matchScheduleInfo.getTwoTime()){
            Map<String,Object> map = new HashMap<>();
            Integer winner0 = m.getWinner0();
            Integer winner1 = m.getWinner1();
            map.put("winner0", winner0);
            map.put("winner1", winner1);
            return ResultUtils.ok(map);
        }

        return ResultUtils.ok();
    }

    @RequestMapping(value = "/next", method = RequestMethod.POST)
    public CommonResult next(@RequestParam(value = "matchScheduleId") int matchScheduleId) {
        List<Map<String,Object>> matchScoreInfoList = matchScoreService.getMatchScoreList(matchScheduleId,1);
        for (Map<String,Object> map : matchScoreInfoList){
            Double expressiveness = (Double) map.get("expressiveness");
            expressiveness = expressiveness + 0.1;
            MatchScore matchScore = new MatchScore();
            matchScore.setId((Integer) map.get("id"));
            matchScore.setExpressiveness(expressiveness);
            matchScoreService.updateById(matchScore);
        }
        return ResultUtils.ok();
    }

    @RequestMapping(value = "/prev", method = RequestMethod.POST)
    public CommonResult prev(@RequestParam(value = "matchScheduleId") int matchScheduleId) {
        List<Map<String,Object>> matchScoreInfoList = matchScoreService.getMatchScoreList(matchScheduleId,1);
        for (Map<String,Object> map : matchScoreInfoList){
            Double expressiveness = (Double) map.get("expressiveness");
            if (expressiveness >= 0.1){
                expressiveness = expressiveness - 0.1;
                MatchScore matchScore = new MatchScore();
                matchScore.setId((Integer) map.get("id"));
                matchScore.setExpressiveness(expressiveness);
                matchScoreService.updateById(matchScore);
            }
        }
        return ResultUtils.ok();
    }


    @RequestMapping(value = "/saveSocre", method = RequestMethod.POST)
    public CommonResult saveSocre( int id, int matchScheduleId, double expressiveness,
              double accuracy, String referee,
              Integer refereeId,
              int scoreType, int winner) {

        String countdown = (String) redisTemplate.opsForValue().get("countdown"+matchScheduleId);
        if (countdown == null){
        //    return ResultUtils.error(50,"比赛未开始");
        }
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);
        if (matchScheduleInfo.getIsLocked() == 1){
            MatchScore matchScore = new MatchScore();
            matchScore.setMatchScheduleId(matchScheduleId);
            if (matchScheduleInfo.getType() == 1 || (matchScheduleInfo.getType() == 2 && matchScheduleInfo.getTwoTime())){
                matchScore.setExpressiveness(expressiveness);
                matchScore.setAccuracy(accuracy);
            }
            matchScore.setCreateTime(new Date());
            matchScore.setReferee(referee);
            matchScore.setRefereeId(refereeId);
            if (matchScheduleInfo.getType() == 2 && !matchScheduleInfo.getTwoTime()){
                matchScore.setWinner(winner);
            }
            matchScore.setId(id);
            matchScore.setScoreType(matchScheduleInfo.getLockTwoTime());
            matchScoreService.saveOrUpdate(matchScore);

            Integer refereeCount = matchRefereeService.selectRefereeCount(matchScheduleInfo.getMatchId());
            List<Map<String,Object>> scoreList = matchScoreService.getMatchScoreList(matchScheduleId,matchScheduleInfo.getLockTwoTime());

            if ((matchScheduleInfo.getRedTeam() == null && matchScheduleInfo.getTwoTime() && matchScheduleInfo.getLockTwoTime() == 1 && scoreList.size() == refereeCount * 2)
                || (matchScheduleInfo.getRedTeam() != null && matchScheduleInfo.getTwoTime() && matchScheduleInfo.getLockTwoTime() == 3 && scoreList.size() == refereeCount * 4)
                || (matchScheduleInfo.getRedTeam() == null && !matchScheduleInfo.getTwoTime() && matchScheduleInfo.getLockTwoTime() == 0 && scoreList.size() == refereeCount)
                || (matchScheduleInfo.getRedTeam() != null && !matchScheduleInfo.getTwoTime() && matchScheduleInfo.getLockTwoTime() == 1 && scoreList.size() == refereeCount * 2)

            ){
                MatchSchedule m = new MatchSchedule();
                SysUserInfo userInfo = userService.getUser(SecurityUtils.getCurrentUserId(request));
                m.setFinalUser(userInfo.getNickName());
                m.setIsComplete(1);
                m.setId(matchScheduleId);
                matchScheduleService.updateById(m);
            }
        }
        return ResultUtils.ok();
    }

    @RequestMapping(value = "/orderTotalScore", method = RequestMethod.POST)
    public CommonResult orderTotalScore(@RequestParam(value = "matchScheduleId") int matchScheduleId){
        MatchScheduleInfo matchScheduleInfo = matchScheduleService.getSchedule(matchScheduleId);

        Integer ruleId = matchScheduleInfo.getRefereeType();
        MatchScoreOrderRule matchScoreOrderRule = matchScoreOrderRuleService.orderRule(ruleId);
        int orderRuleId = matchScoreOrderRule.getOrderRuleId();
        Integer matchId = matchScheduleInfo.getMatchId();
        List<Map<String,Object>> logicList = matchScheduleLogicScoreService.orderTotalScore(matchScheduleInfo.getScheduleName(),matchId);
        List<Map<String,Object>> resultOrderLogicList = new ArrayList<>();
        for (int k=0;k<logicList.size();k++){
            Map<String,Object> logicMap = logicList.get(k);
            Long total = (Long)logicMap.get("total");
            if (total > 1){
                List<Map<String,Object>> tempList = new ArrayList<>();
                for (int j=0;j<total;j++){
                    Map<String,Object> tempMap = new HashMap<>();
                    Map<String,Object> logicMapJ = logicList.get(k+j);
                    List<Map<String,Object>> orderAccuracyList1 = matchScoreService.orderAccuracyAll((Integer) logicMapJ.get("matchScheduleId"));
                    List<Map<String,Object>> orderExpressivenessList1 = matchScoreService.orderExpressivenessAll((Integer) logicMapJ.get("matchScheduleId"));
                    Map<String,Object> sumScore = matchScoreService.sumScoreAll((Integer) logicMapJ.get("matchScheduleId"));
                    double accuracySum = 0;
                    double expressivenessSum = 0;
                    for (int i = 1; i < orderAccuracyList1.size() - 1; i++) {
                        accuracySum = +(double) orderAccuracyList1.get(i).get("accuracy");
                    }
                    for (int i = 1; i < orderExpressivenessList1.size() - 1; i++) {
                        expressivenessSum = +(double) orderExpressivenessList1.get(i).get("expressiveness");
                    }
                    tempMap.put("id",logicMapJ.get("id"));
                    tempMap.put("index",k+j);
                    tempMap.put("accuracySum",accuracySum);
                    tempMap.put("expressivenessSum",expressivenessSum);
                    tempMap.put("sumScore",(double)sumScore.get("sumP") + (double)sumScore.get("sumA"));
                    tempList.add(tempMap);

                    /*if (matchScheduleInfo.getTwoTime()){

                    }else {
                        List<Map<String,Object>> orderAccuracyList1 = matchScoreService.orderAccuracy((Integer) logicMapJ.get("matchScheduleId"),1);
                        List<Map<String,Object>> orderExpressivenessList1 = matchScoreService.orderExpressiveness((Integer) logicMapJ.get("matchScheduleId"),1);
                        Map<String,Object> sumScore = matchScoreService.sumScore((Integer) logicMapJ.get("matchScheduleId"),1);
                        double accuracySum = 0;
                        double expressivenessSum = 0;
                        for (int i = 1; i < orderAccuracyList1.size() - 1; i++) {
                            accuracySum = +(double) orderAccuracyList1.get(i).get("accuracy");
                        }
                        for (int i = 1; i < orderExpressivenessList1.size() - 1; i++) {
                            expressivenessSum = +(double) orderExpressivenessList1.get(i).get("expressiveness");
                        }
                        tempMap.put("id",logicMapJ.get("id"));
                        tempMap.put("index",k+j);
                        tempMap.put("accuracySum",accuracySum);
                        tempMap.put("expressivenessSum",expressivenessSum);
                        tempMap.put("sumScore",(double)sumScore.get("sumP") + (double)sumScore.get("sumA"));
                        tempList.add(tempMap);
                    }*/
                }
                orderListIndexTemp = new ArrayList<>();
                List<Map<String,Object>> orderTotalIndexTemp = orderListIndex(tempList,orderRuleId);
                for (int i=0;i<orderTotalIndexTemp.size();i++){
                    resultOrderLogicList.add(logicList.get((Integer) orderTotalIndexTemp.get(i).get("index")));
                }
                k = k+Integer.valueOf(total+"");
            }else {
                resultOrderLogicList.add(logicMap);
            }
            if (k+total > 8){
                break;
            }
        }
        List<Map<String,Object>> resultList = new ArrayList<>();
        for (int i=resultOrderLogicList.size();i<8;i++){
            Map<String,Object> map = new HashMap<>();
            map.put("bluePlayer","");
            map.put("blueTeam","");
            resultOrderLogicList.add(map);
        }
        for (int i=0;i<8;i++){
            resultList.add(resultOrderLogicList.get(i));
        }
        return ResultUtils.ok(resultList);
    }
    private List<Map<String,Object>> orderListIndexTemp = null;
    private List<Map<String,Object>> orderListIndex(List<Map<String,Object>> tempList,int orderRuleId){
        if (orderRuleId == 1){
            Collections.sort(tempList, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Double name1 =(Double)o1.get("accuracySum");//name1是从你list里面拿出来的一个
                    Double name2= (Double)o2.get("accuracySum"); //name1是从你list里面拿出来的第二name
                    return name1.compareTo(name2);
                }
            });
            List<Map<String,Object>> orderTempList = new ArrayList<>();
            for (int j=0;j<tempList.size()-1;j++){
                double accuracySum1 = (double)tempList.get(j).get("accuracySum");
                double accuracySum2 = (double)tempList.get(j+1).get("accuracySum");;
                if (accuracySum1 == accuracySum2) {
                    orderTempList.add(tempList.get(j));
                    orderTempList.add(tempList.get(j+1));
                }else if (accuracySum1>accuracySum2){
                    orderListIndexTemp.add(tempList.get(j));
                    orderListIndexTemp.add(tempList.get(j+1));
                }else {
                    orderListIndexTemp.add(tempList.get(j+1));
                    orderListIndexTemp.add(tempList.get(j));
                }
            }
            if (orderTempList.size() > 0){
                LinkedHashSet<Map<String,Object>> hashSet = new LinkedHashSet<>(orderTempList);
                ArrayList<Map<String,Object>> listWithoutDuplicates = new ArrayList<>(hashSet);
                orderListIndex(listWithoutDuplicates,2);
            }
        }else if (orderRuleId == 2){
            Collections.sort(tempList, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Double name1 =(Double)o1.get("expressivenessSum");//name1是从你list里面拿出来的一个
                    Double name2= (Double)o2.get("expressivenessSum"); //name1是从你list里面拿出来的第二name
                    return name1.compareTo(name2);
                }
            });
            List<Map<String,Object>> orderTempList = new ArrayList<>();
            for (int j=0;j<tempList.size()-1;j++){
                double expressivenessSum1 = (double)tempList.get(j).get("expressivenessSum");
                double expressivenessSum2 = (double)tempList.get(j+1).get("expressivenessSum");;
                if (expressivenessSum1 == expressivenessSum2) {
                    orderTempList.add(tempList.get(j));
                    orderTempList.add(tempList.get(j+1));
                }else if (expressivenessSum1>expressivenessSum2){
                    orderListIndexTemp.add(tempList.get(j));
                    orderListIndexTemp.add(tempList.get(j+1));
                }else {
                    orderListIndexTemp.add(tempList.get(j+1));
                    orderListIndexTemp.add(tempList.get(j));
                }
            }
            if (orderTempList.size() > 0){
                LinkedHashSet<Map<String,Object>> hashSet = new LinkedHashSet<>(orderTempList);
                ArrayList<Map<String,Object>> listWithoutDuplicates = new ArrayList<>(hashSet);
                orderListIndex(listWithoutDuplicates,3);
            }
        }else if (orderRuleId == 3){
            Collections.sort(tempList, new Comparator<Map<String, Object>>(){
                public int compare(Map<String, Object> o1, Map<String, Object> o2) {
                    Double name1 =(Double)o1.get("sumScore");//name1是从你list里面拿出来的一个
                    Double name2= (Double)o2.get("sumScore"); //name1是从你list里面拿出来的第二name
                    return name1.compareTo(name2);
                }
            });
            List<Map<String,Object>> orderTempList = new ArrayList<>();
            for (int j=0;j<tempList.size()-1;j++){
                double accuracySum1 = (double)tempList.get(j).get("sumScore");
                double accuracySum2 = (double)tempList.get(j+1).get("sumScore");;
                if (accuracySum1 == accuracySum2) {
                    orderTempList.add(tempList.get(j));
                    orderTempList.add(tempList.get(j+1));
                }else if (accuracySum1>accuracySum2){
                    orderListIndexTemp.add(tempList.get(j));
                    orderListIndexTemp.add(tempList.get(j+1));
                }else {
                    orderListIndexTemp.add(tempList.get(j+1));
                    orderListIndexTemp.add(tempList.get(j));
                }
            }
            if (orderTempList.size() > 0){
                LinkedHashSet<Map<String,Object>> hashSet = new LinkedHashSet<>(orderTempList);
                ArrayList<Map<String,Object>> listWithoutDuplicates = new ArrayList<>(hashSet);
                orderListIndex(listWithoutDuplicates,1);
            }
        }
        return orderListIndexTemp;
    }

}